import axios, { AxiosInstance } from 'axios'
import EventEmitter from 'events'
class Request extends EventEmitter {
  public service :AxiosInstance = axios.create({
    baseURL: 'http://mockjs.test.cn', // api 的 base_url
    timeout: 500 // 请求超时时间
  });
  constructor() {
    super()
    this.interceptors()
  }
  interceptors() {
    this.service.interceptors.request.use(
      config => {
        return config
      },
      error => {
        return Promise.reject(error)
      }
    )
    this.service.interceptors.response.use(
      response => {
        const code = response.status
        if ((code >= 200 && code < 300) || code === 304) {
          this.emit('HttpStatusSuccess')
          // response.data
          return Promise.resolve(response.data)
        } else {
          // 响应错误逻辑处理 5xx 4xx 等等
          this.emit('HttpStatusFaild')
          return Promise.reject(response)
        }
      },
      error => {
        // 响应错误逻辑处理
        // const code = response.status;
        console.log(error)
        this.emit('HttpStatusFaild')
        return Promise.reject(error)
      }
    )
  }
  get(url: any, params: any) {
    return this.service({
      method: 'get',
      url,
      params
    })
  }
  post(url: any, data: any) {
    return this.service({
      method: 'post',
      url,
      data
    })
  }
  delete(url: any, data: any) {
    return this.service({
      method: 'delete',
      url,
      data
    })
  }
  put(url: any, data: any) {
    return this.service({
      method: 'put',
      url,
      data
    })
  }
  patch(url: any, data: any) {
    return this.service({
      method: 'patch',
      url,
      data
    })
  }
}

const request = new Request()

export default request

